/*
 * @Date: 2022-02-13 14:09:26
 * @LastEditors: xiaole
 * @LastEditTime: 2022-02-13 20:50:26
 */

import { defineComponent, ref, computed, provide } from "vue";
import EditorBlock from './editor-block'
import { registerConfig as config } from '../utils/editor-config'
import { Button } from 'vant';
import './editor.scss'
import './editor-left.scss'
export default defineComponent({

    // {
    //     "type": "r-image",
    //     "option": {
    //       "src": "https://rtvue.oss-cn-beijing.aliyuncs.com/static/icons/4.png",
    //       "width": "100%",
    //       "height": "100px",
    //       "shape": "square",
    //       "borderRadius": 0,
    //       "lazyLoad": true,
    //       "loadingIcon": "photo",
    //       "errorIcon": "error-circle",
    //       "showLoading": true,
    //       "showError": true,
    //       "fade": true,
    //       "webp": false,
    //       "duration": "500ms",
    //       "bgColor": "#f3f4f6"
    //     },
    //     "compStyle": {
    //       "width": "100%"
    //     },
    //     "id": "uYwMxWk0iNJw4mMAJBhGuQq96GwTQWzf"
    //   }

    props: {
        modelValue: {
            type: Object
        }
    },
    emits: [
        'update:modelValue'
    ],
    setup(props, ctx) {

        const data = computed({
            get() {
                return props.modelValue
            },
            set(newValue) {
                ctx.emit('update:modelValue', newValue)
            }
        })

        provide('config', config)
        const containerRef = ref(null)
        let currentComponent = null
        const dragEnter = (e) => {
            e.dataTransfer.drapEffect = 'move' //移动图标
        }
        const dragOver = (e) => {
            e.preventDefault()
        }
        const dragLeave = (e) => {
            e.dataTransfer.drapEffect = 'none'
        }
        const drop = (e) => {
            let blocks = data.value.blocks
            data.value = {
                ...data.value,
                blocks: [
                    ...blocks,
                    {
                        key: currentComponent.key,
                        _id: Math.random().toFixed(6).slice(-6)
                    }
                ]
            }
            currentComponent = null
        }
        const dragStart = (e, component) => {
            console.log(containerRef.value)
            // ● dragEnter：进入元素中，增加可移动标识（class调整cursor属性）
            // ● dragOver：目标元素中经过（必须阻止默认行为，否则不能触发drop：e.preventDefault）
            // ● dragLeave：离开目标元素的时候，增加禁用标识（class调整cursor属性）
            // ● drop：松手的时候，（根据拖拽的组件）添加一个组件
            // ● dragEnd：拖拽完毕，事件销毁。
            containerRef.value.addEventListener('dragenter', dragEnter)
            containerRef.value.addEventListener('dragover', dragOver)
            containerRef.value.addEventListener('dragleave', dragLeave)
            containerRef.value.addEventListener('drop', drop)
            currentComponent = component
        }
        const generate = () => {
            console.log('代码结构：', JSON.stringify(data.value.blocks))
        }

        const blockMousedown = (e, block, index) => {
            e.preventDefault()
            e.stopPropagation()
            data.value.blocks.forEach(item => item.focus = false)
            data.value.blocks[index].focus = block.focus ? !block.focus : true
            selectIndex.value = index
        }
        const deleteComponent = block => {
            data.value.blocks.forEach((item, index) => {
                if (item._id == block._id) {
                    console.log(item._id, block._id)
                    data.value.blocks.splice(index, 1)
                }
            })
        }

        const reset = () => {
            data.value.blocks = []
        }

        return () =>
            <div class="editor-wrapper">
                <div class="editor-left">
                    {
                        config.componentList.map(component => {
                            return <div
                                class="proview-item"
                                draggable
                                onDragstart={e => dragStart(e, component)}
                            >
                                <span>{component.lebal}</span>
                                <div> {component.render()}</div>
                            </div>
                        })
                    }

                </div>
                <div class="editor-center" ref={containerRef}>
                    {
                        data.value.blocks.map((block, index) => (
                            <div class={block.focus ? 'editor-active editor-block-focus' : 'editor-active'}>
                                <EditorBlock block={block} onMousedown={(e) => blockMousedown(e, block, index)} />
                                {block.focus && <div onClick={index => deleteComponent(block)} class="editor-active-clear">x</div>}
                            </div>
                        ))
                    }
                </div>

                <div>

                    属性控制栏
                    <div><Button type="primary" size="large" onClick={() => generate()}>生成代码</Button></div>
                    <div><Button type="primary" size="large" onClick={() => reset()}>重做</Button></div>
                </div>


            </div>
    }
})